package com.cjd.common.utils

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.text.TextUtils

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/12/11
 * description 监听activity 声明周期 用于特殊线程 停止或判断
 */
object ActivityLifecycleCallbacksUtil {

    @JvmField
    var NOW_INTERRUPT_MAP = mutableMapOf<String, Boolean>()

    fun setNowInterrupt(simpleName: String, isInterrupt: Boolean = false) {
        if (!TextUtils.isEmpty(simpleName)) {
            NOW_INTERRUPT_MAP[simpleName] = isInterrupt
        }
    }

    fun isNowInterrupt(simpleName: String?): Boolean {
        return NOW_INTERRUPT_MAP[simpleName] ?: false
    }

    private val callback: Application.ActivityLifecycleCallbacks =
        object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {

            }

            override fun onActivityResumed(activity: Activity?) {

            }

            override fun onActivityStarted(activity: Activity?) {

            }

            override fun onActivityDestroyed(activity: Activity?) {
                activity?.let {
                    val simpleName = it::class.java.simpleName

                    NOW_INTERRUPT_MAP[simpleName] = true
                    LogUtils.d("--->$simpleName destroyed()")
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {

            }

            override fun onActivityStopped(activity: Activity?) {

            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
                activity?.let {
                    val simpleName = it::class.java.simpleName
                    NOW_INTERRUPT_MAP[simpleName] = false
                    LogUtils.d("--->$simpleName created()")

                }
            }

        }

    fun register(application: Application) {
        application.registerActivityLifecycleCallbacks(callback)
    }

    fun unregister(application: Application) {
        application.unregisterActivityLifecycleCallbacks(callback)
    }
}